<!--
  * 实训室耗材审批管理
  *
  * @Author:    王俊权
  * @Date:      2024-11-06 10:32:23
  * @Copyright  🐂🐎bloc
-->
<template>
  <a-modal
      :title="form.id ? '编辑' : '添加'"
      :width="500"
      :open="visibleFlag"
      @cancel="onClose"
      :maskClosable="false"
      :destroyOnClose="true"
  >
    <fieldset :disabled="isApproval">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
      <a-form-item label="采购日期" name="purchaseDate">
        <a-date-picker show-time valueFormat="YYYY-MM-DD HH:mm:ss" v-model:value="form.purchaseDate" style="width: 100%"
                       placeholder="采购日期"/>
      </a-form-item>
      <a-form-item label="请购部门" name="department">
        <a-input style="width: 100%" v-model:value="form.department" placeholder="请购部门"  disabled/>
      </a-form-item>
      <a-form-item label="申请人" name="applicant">
<!--        <a-input style="width: 100%" v-model:="formState.managerId" placeholder="申请人"/>-->
          <EmployeeSelect ref="employeeSelect" placeholder="请选择部门负责人" width="100%" v-model:value="form.applicant"   :showDepartment="false" @send:Department="getDepartment"/>


      </a-form-item>
      <a-form-item label="申请人电话" name="applicantPhone">
        <a-input style="width: 100%" v-model:value="form.applicantPhone" placeholder="申请人电话"  disabled/>
      </a-form-item>
      <a-form-item label="耗材名称" name="materialName">
        <a-input style="width: 100%" v-model:value="form.materialName" placeholder="耗材名称"/>
      </a-form-item>

      <a-form-item label="耗材编码" name="materialCode">
        <a-input style="width: 100%" v-model:value="form.materialCode" placeholder="耗材编码"/>
      </a-form-item>
      <a-form-item label="类型" name="category">
<!--        <a-input style="width: 100%" v-model:value="form.category" placeholder="耗材类别"/>-->
        <CategoryTree v-model:value="form.category" placeholder="请选择商品分类"
                      :categoryType="CATEGORY_TYPE_ENUM.category.value"/>
      </a-form-item>
      <a-form-item label="规格" name="specification">
        <a-input style="width: 100%" v-model:value="form.specification" placeholder="规格"/>
      </a-form-item>
      <a-form-item label="单位" name="unit">
        <a-input style="width: 100%" v-model:value="form.unit" placeholder="单位"/>
      </a-form-item>
      <a-form-item label="数量" name="quantity">
        <a-input-number style="width: 100%" v-model:value="form.quantity" placeholder="数量"/>
      </a-form-item>
      <a-form-item label="单价（元）" name="unitPrice">
        <a-input-number style="width: 100%" v-model:value="form.unitPrice" placeholder="单价（元）"/>
      </a-form-item>
      <a-form-item label="金额（元）" name="totalAmount">
        <a-input-number style="width: 100%" v-model:value="form.totalAmount" placeholder="金额（元）"/>
      </a-form-item>
      <a-form-item label="存放地点" name="storageLocation">
        <a-input style="width: 100%" v-model:value="form.storageLocation" placeholder="存放地点"/>
      </a-form-item>
      <a-form-item label="预算采购金额（元）" name="budgetAmount">
        <a-input-number style="width: 100%" v-model:value="form.budgetAmount" placeholder="预算采购金额（元）"/>
      </a-form-item>
      <a-form-item label="采购途径" name="purchaseChannel">
        <a-input style="width: 100%" v-model:value="form.purchaseChannel" placeholder="采购途径"/>
      </a-form-item>
      <a-form-item label="经费项目名称" name="projectName">
        <a-input style="width: 100%" v-model:value="form.projectName" placeholder="经费项目名称"/>
      </a-form-item>
      <a-form-item label="经费项目编号" name="projectId">
        <a-input style="width: 100%" v-model:value="form.projectId" placeholder="经费项目编号"/>
      </a-form-item>
      <a-form-item label="使用部门副职意见" name="deputyHeadOpinion" v-if="useUserStore().administratorFlag"
                   v-privilege="'consum:input:query'">
<!--        <a-input style="width: 100%" v-model:value="form.deputyHeadOpinion"-->
<!--                 placeholder="使用部门副职意见（包括签名和日期）0表示不同意 1表示同意"/>-->
        <a-radio-group v-model:value="form.deputyHeadOpinion">
          <a-radio :value="0">不同意</a-radio>
          <a-radio :value="1">同意</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="使用部门正职意见" name="headOpinion"
                   v-privilege="'consum:input:query'"  v-if="useUserStore().administratorFlag">
<!--        <a-input style="width: 100%" v-model:value="form.headOpinion"-->
<!--                 placeholder="使用部门正职意见（包括签名和日期）0表示不同意 1表示同意"/>-->
        <a-radio-group v-model:value="form.headOpinion">
          <a-radio :value="0">不同意</a-radio>
          <a-radio :value="1">同意</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="moneyShow && useUserStore().administratorFlag" label="职能部门意见" name="functionDepartmentOpinion"
                   v-privilege="'consum:input:query'"  >
<!--        <a-input style="width: 100%" v-model:value="form.functionDepartmentOpinion"-->
<!--                 placeholder="职能部门意见（大于2万元，包括签名和日期）0表示不同意 1表示同意"/>-->
        <a-radio-group v-model:value="form.functionDepartmentOpinion">
            <a-radio :value="0">不同意</a-radio>
            <a-radio :value="1">同意</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="moneyShow && useUserStore().administratorFlag" label="教学主管领导意见" name="teachingLeaderOpinion"
                   v-privilege="'consum:input:query'">
<!--        <a-input style="width: 100%" v-model:value="form.teachingLeaderOpinion"-->
<!--                 placeholder="教学主管领导意见（大于2万元，包括签名和日期）0表示不同意 1表示同意"/>-->
        <a-radio-group v-model:value="form.teachingLeaderOpinion">
          <a-radio :value="0">不同意</a-radio>
          <a-radio :value="1">同意</a-radio>
        </a-radio-group>

      </a-form-item>
<!--      <a-form-item label="审核状态，pending表示待审核，approved表示已批准，rejected表示已拒绝" name="approvalStatus"-->
<!--                   v-privilege="'consum:input:query'">-->
<!--        <a-input style="width: 100%" v-model:value="form.approvalStatus"-->
<!--                 placeholder="审核状态，pending表示待审核，approved表示已批准，rejected表示已拒绝"/>-->
<!--      </a-form-item>-->
    </a-form>
    </fieldset>
    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
import {reactive, ref, nextTick, onMounted, computed, watch, toRefs} from 'vue';
import _ from 'lodash';
import {message} from 'ant-design-vue';
import {SmartLoading} from '/src/components/framework/smart-loading';
import {
  consumablesPurchaseApprovalApi
} from '/@/api/business/consumables-purchase-approval/consumables-purchase-approval-api';
import {smartSentry} from '/src/lib/smart-sentry';
import {useUserStore} from "/@/store/modules/system/user.js";
import EmployeeSelect from '/@/components/system/employee-select/index.vue';
import CategoryTree from '/@/components/business/category-tree-select/index.vue';

// ------------------------ 事件 ------------------------
const isApproval = computed(() => {
  return form.approvalStatus == 1 || form.approvalStatus == 2
})
const emits = defineEmits(['reloadList']);

const USAM= useUserStore()

const actName = ref()

const applicant=ref()

const moneyShow = ref(false)

const CATEGORY_TYPE_ENUM = {
  category: {
    value: 2,
    desc: '类别',
  },
}


// ------------------------ 显示与隐藏 ------------------------
// 是否显示
const visibleFlag = ref(false);

function show(rowData) {
  Object.assign(form, formDefault);
  if (rowData && !_.isEmpty(rowData)) {
    Object.assign(form, rowData);
  }

  // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
  // if (form.status && form.status.length > 0) {
  //   form.status = form.status.map((e) => e.valueCode);
  // }
  visibleFlag.value = true;

  nextTick(() => {
    formRef.value.clearValidate();
    applicant.value = USAM.actualName
    console.log('ac',applicant.value)
  });
}

function onClose() {
  Object.assign(form, formDefault);
  visibleFlag.value = false;
}

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();

// const departmentTreeSelect = ref();
const defaultDepartmentForm = {
  managerId: undefined, //部门负责人
};

const employeeSelect = ref();

let formState = reactive({
  ...defaultDepartmentForm,
});



const formDefault = {
  id:undefined,
  purchaseDate: undefined, //采购日期
  department: undefined, //请购部门
  applicant: undefined, //申请人
  actualName:undefined,
  applicantPhone: undefined, //申请人电话
  serialNumber: undefined, //序号
  materialName: undefined, //耗材名称
  specification: undefined, //规格
  quantity: undefined, //数量
  unitPrice: undefined, //单价（元）
  totalAmount: undefined, //金额（元）
  storageLocation: undefined, //存放地点
  budgetAmount: undefined, //预算采购金额（元）
  projectName: undefined, //经费项目名称
  projectId: undefined, //经费项目编号
  approvalStatus: undefined, //审核状态
  purchaseChannel: undefined, //采购途径
  unit: undefined, //单位
  category: undefined, //类别
  materialCode: undefined, //耗材编码
};

const adminRules = {
  deputyHeadOpinion: undefined, //使用部门副职意见（包括签名和日期）0表示不同意 1表示同意
  headOpinion: undefined, //使用部门正职意见（包括签名和日期）0表示不同意 1表示同意
  functionDepartmentOpinion: undefined, //职能部门意见（大于2万元，包括签名和日期）0表示不同意 1表示同意
  teachingLeaderOpinion: undefined, //教学主管领导意见（大于2万元，包括签名和日期）0表示不同意 1表示同意
}

let form = reactive({...formDefault, ...adminRules});
const {department,applicantPhone} = toRefs(form)
const rules = {
  purchaseDate: [{required: true, message: '采购日期 必填'}],
  department: [{required: true, message: '请购部门 必填'}],
  actualName	: [{required: true, message: '申请人 必填'}],

  applicantPhone: [{required: true, message: '申请人电话 必填'}],
  serialNumber: [{required: true, message: '序号 必填'}],
  materialName: [{required: true, message: '耗材名称 必填'}],
  quantity: [{required: true, message: '数量 必填'}],
  unitPrice: [{required: true, message: '单价（元） 必填'}],
  totalAmount: [{required: true, message: '金额（元） 必填'}],
  storageLocation: [{required: true, message: '存放地点 必填'}],
  budgetAmount: [{required: true, message: '预算采购金额（元） 必填'}],
  projectName: [{required: true, message: '经费项目名称 必填'}],
  projectId: [{required: true, message: '经费项目编号 必填'}],
  category: [{required: true, message: '类别 必填'}],
  materialCode: [{required: true, message: '耗材编码 必填'}],
  // approvalStatus: [{required: true, message: '审核状态，pending表示待审核，approved表示已批准，rejected表示已拒绝 必填'}],
};
// deputyHeadOpinion: [{ required: true, message: '使用部门副职意见（包括签名和日期）0表示不同意 1表示同意 必填' }],
//     headOpinion: [{ required: true, message: '使用部门正职意见（包括签名和日期）0表示不同意 1表示同意 必填' }],
//     functionDepartmentOpinion: [{ required: true, message: '职能部门意见（大于2万元，包括签名和日期）0表示不同意 1表示同意 必填' }],
//     teachingLeaderOpinion: [{ required: true, message: '教学主管领导意见（大于2万元，包括签名和日期）0表示不同意 1表示同意 必填' }],
// 点击确定，验证表单
async function onSubmit() {
  if(isApproval.value){
    return message.error('已审批，不可修改')
  }
  try {
    await formRef.value.validateFields();
    save();
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}

// 新建、编辑API
async function save() {
  SmartLoading.show();
  try {
    if (form.id) {
      await consumablesPurchaseApprovalApi.update(form);
    } else {
      await consumablesPurchaseApprovalApi.add(form);
    }
    message.success('操作成功');
    emits('reloadList');
    onClose();
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    SmartLoading.hide();
  }
}

defineExpose({
  show,
});

watch(()=>actName.value,(val)=>{
  applicant.value = val
  form.applicant=val
  // console.log('form',form.applicant)
},{immediate:true})

watch(()=>form.budgetAmount,(val)=>{
  // console.log('val',val)
  if (Number(val)  > 20000 ) {
    moneyShow.value = true
  }else {
    moneyShow.value = false
  }
},{immediate:true,deep:true})
const getDepartment = (value)=>{
  department.value = value.departmentName
  applicantPhone.value = value.phone
}

onMounted(()=>{
  actName.value = USAM.actualName

})
</script>
